package com.lanvideo.controller;

import com.lanvideo.entity.Video;
import com.lanvideo.service.VideoService;
import com.lanvideo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 视频控制器
 */
@RestController
@RequestMapping("/api/video")
public class VideoController {

    @Autowired
    private VideoService videoService;

    @Autowired
    private UserService userService;

    /**
     * 上传视频（老师/管理员功能）
     */
    @PostMapping("/upload")
    public ResponseEntity<Map<String, Object>> uploadVideo(
            @RequestParam("file") MultipartFile file,
            @RequestParam("title") String title,
            @RequestParam(value = "intro", required = false) String intro,
            @RequestParam(value = "tags", required = false) String tags,
            HttpSession session) {
        
        Map<String, Object> result = new HashMap<>();
        
        // 检查用户权限
        Integer userRole = (Integer) session.getAttribute("userRole");
        if (userRole == null || (userRole != 0 && userRole != 1)) {
            result.put("success", false);
            result.put("message", "权限不足，只有老师和管理员可以上传视频");
            return ResponseEntity.ok(result);
        }
        
        Integer userId = (Integer) session.getAttribute("userId");
        if (userId == null) {
            result.put("success", false);
            result.put("message", "用户未登录");
            return ResponseEntity.ok(result);
        }
        
        // 检查文件是否为空
        if (file.isEmpty()) {
            result.put("success", false);
            result.put("message", "请选择要上传的文件");
            return ResponseEntity.ok(result);
        }
        
        // 检查文件类型
        String contentType = file.getContentType();
        if (contentType == null || !contentType.startsWith("video/")) {
            result.put("success", false);
            result.put("message", "请上传视频文件");
            return ResponseEntity.ok(result);
        }
        
        boolean success = videoService.uploadVideo(file, title, intro, tags, userId);
        if (success) {
            result.put("success", true);
            result.put("message", "视频上传成功");
        } else {
            result.put("success", false);
            result.put("message", "视频上传失败");
        }
        
        return ResponseEntity.ok(result);
    }

    /**
     * 获取所有已审核通过的视频（需要登录）
     */
    @GetMapping("/all")
    public ResponseEntity<Map<String, Object>> getAllVideos(HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        
        // 检查用户是否已登录
        Integer userRole = (Integer) session.getAttribute("userRole");
        if (userRole == null) {
            result.put("success", false);
            result.put("message", "请先登录");
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(result);
        }
        
        List<Video> videos = videoService.getAllVideos();
        result.put("success", true);
        result.put("videos", videos);
        result.put("count", videos.size());
        return ResponseEntity.ok(result);
    }


    /**
     * 获取所有视频（管理员使用，包括所有状态）
     */
    @GetMapping("/admin/all")
    public ResponseEntity<Map<String, Object>> getAllVideosForAdmin(HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        
        Integer userRole = (Integer) session.getAttribute("userRole");
        if (userRole == null || userRole != 0) {
            result.put("success", false);
            result.put("message", "权限不足，只有管理员可以查看所有视频");
            return ResponseEntity.ok(result);
        }
        
        List<Video> videos = videoService.getAllVideosForAdmin();
        result.put("success", true);
        result.put("videos", videos);
        return ResponseEntity.ok(result);
    }

    /**
     * 根据ID获取视频
     */
    @GetMapping("/{id}")
    public ResponseEntity<Map<String, Object>> getVideoById(@PathVariable Integer id, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        
        Video video = videoService.getVideoById(id);
        if (video == null) {
            result.put("success", false);
            result.put("message", "视频不存在");
            return ResponseEntity.ok(result);
        }
        
        // 获取用户角色和ID（如果已登录）
        Integer userRole = (Integer) session.getAttribute("userRole");
        Integer userId = (Integer) session.getAttribute("userId");
        boolean isAdmin = userRole != null && userRole == 0;
        boolean isTeacher = userRole != null && userRole == 1;
        boolean isStudent = userRole != null && userRole == 2;
        
        // 权限检查逻辑
        if (isAdmin) {
            // 管理员可以查看所有视频
            result.put("success", true);
            result.put("video", video);
        } else if (isTeacher) {
            // 老师可以查看自己发布的所有视频（包括未审核的）
            if (userId != null && userId.equals(video.getUploaderId())) {
                result.put("success", true);
                result.put("video", video);
            } else {
                // 老师只能查看已审核通过的视频
                if (video.getStatus() != null && video.getStatus() == 1) {
                    result.put("success", true);
                    result.put("video", video);
                } else {
                    result.put("success", false);
                    result.put("message", "只能查看自己的视频或已审核通过的视频");
                }
            }
        } else if (isStudent) {
            // 学生只能查看已审核通过的视频
            if (video.getStatus() != null && video.getStatus() == 1) {
                result.put("success", true);
                result.put("video", video);
            } else {
                result.put("success", false);
                result.put("message", "视频暂不可访问，请等待审核");
            }
        } else {
            // 未登录用户不能访问任何视频
            result.put("success", false);
            result.put("message", "请先登录");
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(result);
        }
        
        return ResponseEntity.ok(result);
    }

    /**
     * 搜索视频（需要登录）
     */
    @GetMapping("/search")
    public ResponseEntity<Map<String, Object>> searchVideos(@RequestParam String keyword, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        
        // 检查用户是否已登录
        Integer userRole = (Integer) session.getAttribute("userRole");
        if (userRole == null) {
            result.put("success", false);
            result.put("message", "请先登录");
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(result);
        }
        
        List<Video> videos = videoService.searchVideos(keyword);
        result.put("success", true);
        result.put("videos", videos);
        result.put("count", videos.size());
        return ResponseEntity.ok(result);
    }

    /**
     * 高级搜索视频（学生使用）
     */
    @PostMapping("/advanced-search")
    public ResponseEntity<Map<String, Object>> advancedSearchVideos(@RequestBody Map<String, Object> searchParams, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        
        // 检查用户是否已登录
        Integer userRole = (Integer) session.getAttribute("userRole");
        if (userRole == null) {
            result.put("success", false);
            result.put("message", "请先登录");
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(result);
        }
        
        try {
            String title = (String) searchParams.get("title");
            String uploader = (String) searchParams.get("uploader");
            String tags = (String) searchParams.get("tags");
            String intro = (String) searchParams.get("intro");
            
            List<Video> videos = videoService.advancedSearchVideos(title, uploader, tags, intro);
            result.put("success", true);
            result.put("videos", videos);
            result.put("count", videos.size());
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "搜索失败：" + e.getMessage());
            return ResponseEntity.ok(result);
        }
    }

    /**
     * 高级搜索视频（管理员和老师使用）
     */
    @PostMapping("/advanced-search-all")
    public ResponseEntity<Map<String, Object>> advancedSearchAllVideos(@RequestBody Map<String, Object> searchParams, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        
        // 检查用户是否已登录
        Integer userRole = (Integer) session.getAttribute("userRole");
        if (userRole == null) {
            result.put("success", false);
            result.put("message", "请先登录");
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(result);
        }
        
        // 只有管理员和老师可以使用此接口
        if (userRole != 0 && userRole != 1) {
            result.put("success", false);
            result.put("message", "权限不足");
            return ResponseEntity.status(HttpStatus.FORBIDDEN).body(result);
        }
        
        try {
            String title = (String) searchParams.get("title");
            String uploader = (String) searchParams.get("uploader");
            String tags = (String) searchParams.get("tags");
            String intro = (String) searchParams.get("intro");
            Integer status = null;
            
            if (searchParams.get("status") != null) {
                status = Integer.valueOf(searchParams.get("status").toString());
            }
            
            List<Video> videos = videoService.advancedSearchAllVideos(title, uploader, tags, intro, status);
            result.put("success", true);
            result.put("videos", videos);
            result.put("count", videos.size());
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "搜索失败：" + e.getMessage());
            return ResponseEntity.ok(result);
        }
    }

    /**
     * 获取我的视频（上传者功能）
     */
    @GetMapping("/my")
    public ResponseEntity<Map<String, Object>> getMyVideos(HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        
        Integer userRole = (Integer) session.getAttribute("userRole");
        if (userRole == null || (userRole != 0 && userRole != 1)) {
            result.put("success", false);
            result.put("message", "权限不足");
            return ResponseEntity.ok(result);
        }
        
        Integer userId = (Integer) session.getAttribute("userId");
        if (userId == null) {
            result.put("success", false);
            result.put("message", "用户未登录");
            return ResponseEntity.ok(result);
        }
        
        List<Video> videos = videoService.getVideosByUploaderId(userId);
        result.put("success", true);
        result.put("videos", videos);
        
        return ResponseEntity.ok(result);
    }

    /**
     * 删除视频（上传者功能）
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Map<String, Object>> deleteVideo(@PathVariable Integer id, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        
        Integer userRole = (Integer) session.getAttribute("userRole");
        if (userRole == null || (userRole != 0 && userRole != 1)) {
            result.put("success", false);
            result.put("message", "权限不足");
            return ResponseEntity.ok(result);
        }
        
        Integer userId = (Integer) session.getAttribute("userId");
        if (userId == null) {
            result.put("success", false);
            result.put("message", "用户未登录");
            return ResponseEntity.ok(result);
        }
        
        // 检查视频是否存在且属于当前用户
        Video video = videoService.getVideoById(id);
        if (video == null) {
            result.put("success", false);
            result.put("message", "视频不存在");
            return ResponseEntity.ok(result);
        }
        
        // 管理员可以删除任何视频，老师只能删除自己的视频
        if (userRole != 0 && !video.getUploaderId().equals(userId)) {
            result.put("success", false);
            result.put("message", "只能删除自己的视频");
            return ResponseEntity.ok(result);
        }
        
        boolean success = videoService.deleteVideo(id);
        if (success) {
            result.put("success", true);
            result.put("message", "视频删除成功");
        } else {
            result.put("success", false);
            result.put("message", "视频删除失败");
        }
        
        return ResponseEntity.ok(result);
    }

    /**
     * 更新视频信息
     */
    @PostMapping("/update")
    public ResponseEntity<Map<String, Object>> updateVideo(@RequestBody Video video, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        
        Integer userRole = (Integer) session.getAttribute("userRole");
        if (userRole == null || (userRole != 0 && userRole != 1)) {
            result.put("success", false);
            result.put("message", "权限不足");
            return ResponseEntity.ok(result);
        }
        
        Integer userId = (Integer) session.getAttribute("userId");
        if (userId == null) {
            result.put("success", false);
            result.put("message", "用户未登录");
            return ResponseEntity.ok(result);
        }
        
        // 检查视频是否存在且属于当前用户
        Video existingVideo = videoService.getVideoById(video.getId());
        if (existingVideo == null) {
            result.put("success", false);
            result.put("message", "视频不存在");
            return ResponseEntity.ok(result);
        }
        
        // 管理员可以修改任何视频，老师只能修改自己的视频
        if (userRole != 0 && !existingVideo.getUploaderId().equals(userId)) {
            result.put("success", false);
            result.put("message", "只能修改自己的视频");
            return ResponseEntity.ok(result);
        }
        
        boolean success = videoService.updateVideo(video);
        if (success) {
            result.put("success", true);
            result.put("message", "视频信息更新成功");
        } else {
            result.put("success", false);
            result.put("message", "视频信息更新失败");
        }
        
        return ResponseEntity.ok(result);
    }

    /**
     * 获取待审核视频（管理员功能）
     */
    @GetMapping("/pending")
    public ResponseEntity<Map<String, Object>> getPendingVideos(HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        
        Integer userRole = (Integer) session.getAttribute("userRole");
        if (userRole == null || userRole != 0) {
            result.put("success", false);
            result.put("message", "权限不足，只有管理员可以查看待审核视频");
            return ResponseEntity.ok(result);
        }
        
        List<Video> pendingVideos = videoService.getPendingVideos();
        
        // 调试日志
        System.out.println("=== VideoController.getPendingVideos Debug ===");
        System.out.println("User Role: " + userRole);
        System.out.println("Found " + pendingVideos.size() + " pending videos");
        for (Video video : pendingVideos) {
            System.out.println("Video ID: " + video.getId() + 
                ", Title: " + video.getTitle() + 
                ", Status: " + video.getStatus() + 
                ", Uploader: " + video.getUploaderName());
        }
        System.out.println("=== End Debug ===");
        
        result.put("success", true);
        result.put("videos", pendingVideos);
        
        return ResponseEntity.ok(result);
    }

    /**
     * 审核通过视频（管理员功能）
     */
    @PostMapping("/{id}/approve")
    public ResponseEntity<Map<String, Object>> approveVideo(@PathVariable Integer id, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        
        Integer userRole = (Integer) session.getAttribute("userRole");
        if (userRole == null || userRole != 0) {
            result.put("success", false);
            result.put("message", "权限不足，只有管理员可以审核视频");
            return ResponseEntity.ok(result);
        }
        
        boolean success = videoService.approveVideo(id);
        if (success) {
            result.put("success", true);
            result.put("message", "视频审核通过");
        } else {
            result.put("success", false);
            result.put("message", "视频审核失败");
        }
        
        return ResponseEntity.ok(result);
    }

    /**
     * 审核拒绝视频（管理员功能）
     */
    @PostMapping("/{id}/reject")
    public ResponseEntity<Map<String, Object>> rejectVideo(@PathVariable Integer id, 
                                                          @RequestBody(required = false) Map<String, String> requestData,
                                                          HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        
        Integer userRole = (Integer) session.getAttribute("userRole");
        if (userRole == null || userRole != 0) {
            result.put("success", false);
            result.put("message", "权限不足，只有管理员可以审核视频");
            return ResponseEntity.ok(result);
        }
        
        String reason = requestData != null ? requestData.get("reason") : "不符合要求";
        boolean success = videoService.rejectVideo(id, reason);
        if (success) {
            result.put("success", true);
            result.put("message", "视频审核拒绝");
        } else {
            result.put("success", false);
            result.put("message", "视频审核失败");
        }
        
        return ResponseEntity.ok(result);
    }

    /**
     * 老师查看视频详情
     */
    @GetMapping("/teacher/{videoId}")
    public ResponseEntity<Map<String, Object>> getTeacherVideoDetail(@PathVariable Integer videoId, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        try {
            Integer userId = (Integer) session.getAttribute("userId");
            if (userId == null || userService.getUserById(userId).getRole() != 1) {
                result.put("success", false);
                result.put("message", "只有老师可以查看视频详情");
                return ResponseEntity.ok(result);
            }
            
            Video video = videoService.getVideoById(videoId);
            if (video == null) {
                result.put("success", false);
                result.put("message", "视频不存在");
                return ResponseEntity.ok(result);
            }
            
            result.put("success", true);
            result.put("video", video);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "系统错误：" + e.getMessage());
        }
        return ResponseEntity.ok(result);
    }

    /**
     * 管理员查看视频详情
     */
    @GetMapping("/admin/{videoId}")
    public ResponseEntity<Map<String, Object>> getAdminVideoDetail(@PathVariable Integer videoId, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        try {
            Integer userId = (Integer) session.getAttribute("userId");
            if (userId == null || userService.getUserById(userId).getRole() != 0) {
                result.put("success", false);
                result.put("message", "只有管理员可以查看视频详情");
                return ResponseEntity.ok(result);
            }
            
            Video video = videoService.getVideoById(videoId);
            if (video == null) {
                result.put("success", false);
                result.put("message", "视频不存在");
                return ResponseEntity.ok(result);
            }
            
            result.put("success", true);
            result.put("video", video);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "系统错误：" + e.getMessage());
        }
        return ResponseEntity.ok(result);
    }

    /**
     * 获取相关视频（老师端）
     */
    @GetMapping("/teacher/related")
    public ResponseEntity<Map<String, Object>> getTeacherRelatedVideos(HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        try {
            Integer userId = (Integer) session.getAttribute("userId");
            if (userId == null || userService.getUserById(userId).getRole() != 1) {
                result.put("success", false);
                result.put("message", "只有老师可以查看相关视频");
                return ResponseEntity.ok(result);
            }
            
            List<Video> videos = videoService.getApprovedVideos();
            result.put("success", true);
            result.put("videos", videos);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "系统错误：" + e.getMessage());
        }
        return ResponseEntity.ok(result);
    }

    /**
     * 管理员审核通过视频
     */
    @PutMapping("/admin/approve/{videoId}")
    public ResponseEntity<Map<String, Object>> adminApproveVideo(@PathVariable Integer videoId, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        try {
            Integer userId = (Integer) session.getAttribute("userId");
            if (userId == null || userService.getUserById(userId).getRole() != 0) {
                result.put("success", false);
                result.put("message", "只有管理员可以审核视频");
                return ResponseEntity.ok(result);
            }
            
            if (videoService.approveVideo(videoId)) {
                result.put("success", true);
                result.put("message", "视频审核通过");
            } else {
                result.put("success", false);
                result.put("message", "视频审核失败");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "系统错误：" + e.getMessage());
        }
        return ResponseEntity.ok(result);
    }

    /**
     * 管理员审核拒绝视频
     */
    @PutMapping("/admin/reject/{videoId}")
    public ResponseEntity<Map<String, Object>> adminRejectVideo(@PathVariable Integer videoId, 
                                                               @RequestBody Map<String, Object> request, 
                                                               HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        try {
            Integer userId = (Integer) session.getAttribute("userId");
            if (userId == null || userService.getUserById(userId).getRole() != 0) {
                result.put("success", false);
                result.put("message", "只有管理员可以审核视频");
                return ResponseEntity.ok(result);
            }
            
            String reason = (String) request.get("reason");
            if (videoService.rejectVideo(videoId, reason)) {
                result.put("success", true);
                result.put("message", "视频审核拒绝");
            } else {
                result.put("success", false);
                result.put("message", "视频审核失败");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "系统错误：" + e.getMessage());
        }
        return ResponseEntity.ok(result);
    }

    /**
     * 管理员删除视频
     */
    @DeleteMapping("/admin/delete/{videoId}")
    public ResponseEntity<Map<String, Object>> adminDeleteVideo(@PathVariable Integer videoId, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        try {
            Integer userId = (Integer) session.getAttribute("userId");
            if (userId == null || userService.getUserById(userId).getRole() != 0) {
                result.put("success", false);
                result.put("message", "只有管理员可以删除视频");
                return ResponseEntity.ok(result);
            }
            
            if (videoService.deleteVideo(videoId)) {
                result.put("success", true);
                result.put("message", "视频删除成功");
            } else {
                result.put("success", false);
                result.put("message", "视频删除失败");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "系统错误：" + e.getMessage());
        }
        return ResponseEntity.ok(result);
    }
}
